from django import http
from django.shortcuts import render
from django.core.cache import cache
# Create your views here.
from django.views import View

from areas.models import Area


class ArearView(View):
    def get(self,request):

        area_id=request.GET.get('area_id')
        if not area_id:
            province_list=cache.get('province_list')
            if province_list:
               return http.JsonResponse({'code':0,'province_list':province_list})
            provinces=Area.objects.filter(parent=None)

            # if
            province_list=[]
            for province in provinces:
                item_dict={
                    "id":province.id,
                    "name":province.name
                }
                province_list.append(item_dict)
                cache.set('province_list',province_list)
            return http.JsonResponse({'code':0,'province_list':province_list})
        else:
            subs=cache.get('subs_%s'%area_id)
            if subs:
                data_dict = {
                    "code": 0,
                    "sub_data": {
                        "subs": subs
                    }
                }
                return  http.JsonResponse(data_dict)
            subs=[]
            cities=Area.objects.filter(parent_id=area_id).all()
            for city in cities:
                item_dict = {
                    "id": city.id,
                    "name": city.name
                }
                subs.append(item_dict)
            data_dict={
                "code":0,
                "sub_data":{
                    "subs":subs
                }
            }
            cache.set('subs_%s'%area_id,subs)
            return http.JsonResponse(data_dict)
